package ldh.fx.adminfx.util;

import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import ldh.fx.adminfx.cell.ObjectTableCellFactory;

import java.math.BigDecimal;
import java.util.List;

public class TableViewUtil {

    public static void width(TableView<?> tableView) {
        double totalWidth = tableView.getColumns().stream().map(tc->tc.getPrefWidth()).reduce(Double::sum).get();
        for (TableColumn tc : tableView.getColumns()) {
            double width = tc.getPrefWidth();
            double rate = BigDecimal.valueOf(width/totalWidth).setScale(2, BigDecimal.ROUND_DOWN).doubleValue() - 0.0003;
            tc.prefWidthProperty().bind(tableView.widthProperty().multiply(rate));
        }
    }

    public static void alignment(Pos alignment, TableView tableView, String... excludeTableColumnNames) {
        ObservableList<TableColumn> tableColumns = tableView.getColumns();
        for (TableColumn tableColumn : tableColumns) {
            boolean isExclude = false;
            for (String excludeTableColumnName : excludeTableColumnNames) {
                if (tableColumn.getText().equals(excludeTableColumnName)) {
                    isExclude = true;
                    break;
                }
            }
            if (!isExclude) {
                tableColumn.setCellFactory(new ObjectTableCellFactory(e -> e, alignment));
            }
        }
    }

    public static void alignment(Pos alignment, TableColumn... tableColumns) {
        for (TableColumn tableColumn : tableColumns) {
            tableColumn.setCellFactory(new ObjectTableCellFactory(e -> e, alignment));
        }
    }

    public static void alignment(Pos alignment, TableView tableView) {
        ObservableList<TableColumn> tableColumns = tableView.getColumns();
        for (TableColumn tableColumn : tableColumns) {
            tableColumn.setCellFactory(new ObjectTableCellFactory(e -> e, alignment));
        }
    }

    public static void alignment(Pos alignment, TableView tableView, TableColumn...excludeTableColumns) {
        ObservableList<TableColumn> tableColumns = tableView.getColumns();
        for (TableColumn tableColumn : tableColumns) {
            boolean isHave = false;
            for(TableColumn ec : excludeTableColumns) {
                if (tableColumn == ec) {
                    isHave = true;
                    break;
                };
            }
            if (isHave) continue;
            tableColumn.setCellFactory(new ObjectTableCellFactory(e -> e, alignment));
        }
    }
}
